package com.hopes.bizz.poll.town.handler;

import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson.JSONObject;
import com.hopes.bizz.common.core.util.CollectionUtils;
import com.hopes.bizz.poll.common.constant.enums.PollModDictEnum;
import com.hopes.bizz.poll.om.entity.BaseOmDataEntity;
import com.hopes.bizz.poll.town.entity.BaseTownOmDataEntity;
import com.hopes.boss.admin.api.resolver.DictResolver;

import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author lyb
 * @version 1.0
 * @description: 用于计算乡镇的平均历史数据
 * @date 2023/9/27 14:09
 */
public class PollTownDataCalculate {

    private static final String DATA_VAL = "val";

    private static final String DATA_KEY = "key";

    private List<? extends BaseOmDataEntity> list;


    public PollTownDataCalculate(List<? extends BaseOmDataEntity> list) {
        this.list = list;
    }


    public List<BaseTownOmDataEntity> calculate() {
        List<BaseTownOmDataEntity> res = new ArrayList<>();

        if (CollectionUtils.isEmpty(this.list)) {
            return res;
        }
        // 按乡镇分组
        Map<Long, List<BaseOmDataEntity>> townDataMap = this.list.stream().collect(Collectors.groupingBy(v -> {
            Long monitorSiteId = v.getMonitorSiteId();
            String townIdStr = DictResolver.getItemLabelByValue(PollModDictEnum.monitor_site_town, monitorSiteId);
            return Long.valueOf(townIdStr);
        }));

        // 按乡镇统计均值
        Iterator<Map.Entry<Long, List<BaseOmDataEntity>>> iterator = townDataMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<Long, List<BaseOmDataEntity>> entry = iterator.next();
            Long townId = entry.getKey();
            List<BaseOmDataEntity> dataList = entry.getValue();
            res.add(calculate(townId, dataList));
        }
        return res;
    }


    private BaseTownOmDataEntity calculate(Long townId, List<BaseOmDataEntity> dataList) {
        BaseTownOmDataEntity baseTownOmDataEntity = new BaseTownOmDataEntity();
        // 去重
        Map<Long, BaseOmDataEntity> map = dataList.stream().collect(Collectors.toMap(BaseOmDataEntity::getMonitorSiteId, Function.identity(), (v1, v2) -> v1));
        Collection<BaseOmDataEntity> omDataList = map.values();

        // 统计每个因子的累加值和次数
        Map<String, Integer> countMap = new HashMap<>();
        Map<String, Double> valMap = new HashMap<>();
        Double aqiValCount = 0d;
        int aqiCount = 0;
        for (BaseOmDataEntity data : omDataList) {
            JSONObject dataJson = data.getDataJson();
            Double aqiData = data.getAqiData();
            if (Objects.nonNull(aqiData) && aqiData > 0d) {
                aqiCount++;
                aqiValCount += aqiData;
            }
            for (String factor : dataJson.keySet()) {
                JSONObject dataObject = dataJson.getJSONObject(factor);
                Double val = dataObject.getDouble(DATA_VAL);
                if (Objects.isNull(val)) {
                    continue;
                }
                valMap.compute(factor, (k, v) -> v == null ? val : v + val);
                countMap.compute(factor, (k, v) -> v == null ? 1 : v + 1);
            }
        }

        JSONObject dataJson = new JSONObject();
        for (String factor : countMap.keySet()) {
            Integer count = countMap.get(factor);
            Double val = valMap.get(factor);
            BigDecimal div = NumberUtil.div(val, count, 3);
            JSONObject data = new JSONObject();
            data.put(DATA_KEY, factor);
            data.put(DATA_VAL, div.doubleValue());
            dataJson.put(factor, data);
        }
        baseTownOmDataEntity.setTownId(townId);
        baseTownOmDataEntity.setDataJson(dataJson);
        if (aqiCount > 0) {
            baseTownOmDataEntity.setAqiData(NumberUtil.div(aqiValCount, Integer.valueOf(aqiCount), 3).doubleValue());
        }
        return baseTownOmDataEntity;
    }
}
